package com.atguigu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.base.BaseDao;
import com.atguigu.base.BaseServiceImpl;
import com.atguigu.dao.DictDao;
import com.atguigu.entity.Dict;
import com.atguigu.service.DictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = DictService.class)
@Transactional
public class DictServiceImpl extends BaseServiceImpl<Dict> implements DictService {
    @Autowired
    private DictDao dictDao;

    @Override
    protected BaseDao<Dict> getEntityDao() {
        return dictDao;
    }

    @Override
    public List<Map<String, Object>> findZnodes(Long id) {
        //1.访问Dao层获取指定id的子节点列表List<Dict>
        List<Dict> dictList = this.dictDao.findListByParentId(id);
        //2.将子节点列表List<Dict>转换为JSON格式List<Map<String, Object>>
        List<Map<String, Object>> znodeList = new ArrayList<Map<String, Object>>();
        for (Dict dict : dictList) {
            Integer count = dictDao.countIsParent(dict.getId());
            Map<String,Object> znode = new HashMap<String, Object>();
            znode.put("id", dict.getId());
            znode.put("name", dict.getName());
            znode.put("isParent", count > 0 ? true : false);
            znodeList.add(znode);
        }
        return znodeList;
    }

    @Override
    public List<Dict> findListByDictCode(String dictCode) {
        //根据dictCode找到该字典信息（其中包含该字典信息的id）
        Dict dict = this.dictDao.getByDictCode(dictCode);
        //根据字典的id获取它的下级字典列表信息
        List<Dict> dictList = this.dictDao.findListByParentId(dict.getId());
        return dictList;
    }

    @Override
    public List<Dict> findListByParentId(Long parentId) {
        List<Dict> dictList = this.dictDao.findListByParentId(parentId);
        return dictList;
    }

    @Override
    public String getNameById(Long id) {
        return this.dictDao.getNameById(id);
    }
}
